package xyz.xtt.schedule.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import lombok.extern.slf4j.Slf4j;
import xyz.xtt.pay.client.request.ConfirmPayOrderRequest;
import xyz.xtt.pay.client.request.FetchUnPaidOrdersRequest;
import xyz.xtt.pay.client.response.TblPayOrderDto;

/**
 * @author dale
 * @date 2025/1/17
 **/
@Service
@Slf4j
@RefreshScope
public class PayOrderService {
	private static final Object CHECK_PAY_STATUS_ENABLE_CACHE_KEY = "NFT:CACHE:CHECK_PAY_STATUS_ENABLE";
	@Autowired
	private InnerService innerService;
	@Value("${pay.order.status.check.task.enable:true}")
	private boolean checkOrderStatusEnable;
	@Autowired
	private StringRedisTemplate redisTemplate;

	/**
	 * 确认支付订单状态
	 */
	public void confirmPayOrderStatus() {
		if (!canCheckOrderStatus()) {
			return;
		}

		log.info("开始执行支付订单状态确认任务");
		FetchUnPaidOrdersRequest fetchRequest = FetchUnPaidOrdersRequest.builder().pageNo(1).pageSize(20).build();
		List<TblPayOrderDto> data = innerService.fetchUnPaidOrders(fetchRequest);
		if (CollectionUtils.isEmpty(data)) {
			log.info("没有待支付订单");
		} else {
			data.forEach(tblPayOrderDto -> {
				log.info("开始处理待支付订单:{}", tblPayOrderDto);
				ConfirmPayOrderRequest confirmRequest = ConfirmPayOrderRequest
						.builder()
						.payOrderId(tblPayOrderDto.getPayOrderId())
						.appUserId(tblPayOrderDto.getAppUserId())
						.build();
				innerService.confirmPayStatus(confirmRequest);
			});
		}
	}

	/**
	 * 是否可以执行订单状态确认
	 * 
	 * @return
	 */
	private boolean canCheckOrderStatus() {
		// 优先检查配置中心
		if (!checkOrderStatusEnable) {
			return false;
		}
		// 检查开关配置缓存
		String cacheConfig = redisTemplate.opsForValue().get(CHECK_PAY_STATUS_ENABLE_CACHE_KEY);
		if (StringUtils.isNotBlank(cacheConfig) && "false".equalsIgnoreCase(cacheConfig)) {
			return false;
		}
		return true;
	}
}
